<?php
declare(strict_types=1);

class Control
{
    public function __construct(){

    }

    public function input($element = '')
    {
        $data = array_merge($_POST, $_GET);
        if(empty($element)) return $data;
        return $data[$element] ?? null;
    }
    /**
     * @param $status int
     * @param $content array
     * @param $msg string
     * @return void
     */
    public function success($status = 1, $content = [], $msg = 'success')
    {
        echo json_encode(['status' => $status , 'content'=> $content , 'msg' => $msg]);
    }
    public function error($status = 0, $content = [], $msg = 'error')
    {
        echo json_encode(['status' => $status, 'content'=> $content, 'msg' => $msg]);
    }
    /**
     * 封装的一个简易的CURL请求
     * @param string $url
     * @param array $data
     * @return bool|string
     */
    public function curl($url, $data)
    {
        $curl = curl_init();
        //SSL证书
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        //URL
        curl_setopt($curl, CURLOPT_URL,$url);
//        curl_setopt($curl, CURLOPT_HEADER, false);    //HEADER
//        curl_setopt($curl, CURLOPT_COOKIE, false); //设定 HTTP 请求中"Cookie: "部分的内容。多个 cookie 用分号分隔，分号后带一个空格(例如， "fruit=apple; colour=red")。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER,false); //将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_TIMEOUT, 300); //允许 CURL 函数执行的最长秒数。
//        curl_setopt($curl, CURLOPT_PORT, false); //用来指定连接端口
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0); //在尝试连接时等待的秒数。设置为0，则无限等待。
        curl_setopt($curl, CURLOPT_UPLOAD, false); //TRUE 准备上传。

        if(!empty($data)){
            curl_setopt($curl, CURLOPT_POST, true);//部数据使用HTTP协议中的 "POST" 操作来发送。
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
    public function view($view_data = [])
    {
        $method = $_GET['m'];
        $class = $_GET['c'];
        $html_path = DIR_VIEW . str_replace('_', '/', $class) . "/" . $method . ".html";
        $view_data = json_encode($view_data);
        $url = $this->getUrl();
        require $html_path;
    }
    public function getUrl() :string
    {
        $url = 'http://';
        if((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ) $url = 'https://';
        return $url . $_SERVER['HTTP_HOST'];
    }
}